package database;

import java.sql.*;

public class DbLebensmittelUpdate {
	
	String nameLebensmittel = "";
	int userID = 0;
	int mengeAlt = 0;
	int mengeDazu = 0;
	String mhd = "";

	public void lebensmittelUpdaten(){
		DbAllgemein dbAllgemein = new DbAllgemein();
		Statement stat = dbAllgemein.initialisieren();
		DbLebensmittelUpdate dbLebensmittelUpdate = new DbLebensmittelUpdate();
		mengeAlt = dbLebensmittelUpdate.collectMengeAusDb();
		
		mhd = convertMhd(mhd);

		try{
			stat.execute("UPDATE `lebensmittelliste` SET `Menge`=" + (mengeDazu + mengeAlt) + ",`MHD`=" + mhd + " WHERE `Name`='" + nameLebensmittel + "' AND `UserID`=" + userID);

		}catch(SQLException e){
			System.out.println("SQL Error");
			System.out.println("SQLException: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("VendorError: " + e.getErrorCode());
		}

	}
	
	public int collectMengeAusDb(){
		DbAllgemein dbAllgemein = new DbAllgemein();
		Statement stat = dbAllgemein.initialisieren();
		ResultSet rs = null;
		
		try{
			rs = stat.executeQuery("SELECT `Name`,`Menge`,`UserID` FROM `lebensmittelliste` WHERE `UserID`=" + userID);
			rs.first();
			while(rs.next()){
				if(nameLebensmittel.equals(rs.getString("Name")));{
					mengeAlt = mengeAlt + rs.getInt("Menge");
				}
			}
			
		}catch(SQLException e){
			System.out.println("SQL Error");
			System.out.println("SQLException: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("VendorError: " + e.getErrorCode());
		}
		
		return mengeAlt;
	}
	
	private String convertMhd(String datum){
		String newMhd = "";
		
		newMhd = mhd.substring(6, 10);
		newMhd = newMhd + mhd.substring(0, 2);
		newMhd = newMhd + mhd.substring(3, 5);	

		return newMhd;
	}

	public String getNameLebensmittel() {
		return nameLebensmittel;
	}

	public void setNameLebensmittel(String nameLebensmittel) {
		this.nameLebensmittel = nameLebensmittel;
	}

	public int getUserID() {
		return userID;
	}

	public void setUserID(int userID) {
		this.userID = userID;
	}

	public int getMengeAlt() {
		return mengeAlt;
	}

	public void setMengeAlt(int mengeAlt) {
		this.mengeAlt = mengeAlt;
	}

	public int getMengeDazu() {
		return mengeDazu;
	}

	public void setMengeDazu(int mengeDazu) {
		this.mengeDazu = mengeDazu;
	}

	public String getMhd() {
		return mhd;
	}

	public void setMhd(String mhd) {
		this.mhd = mhd;
	}
}